package org.summer.lawyer.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.summer.common.core.utils.MapstructUtils;
import org.summer.common.mybatis.core.page.PageQuery;
import org.summer.common.mybatis.core.page.TableDataInfo;
import org.summer.lawyer.constant.enums.PayRefundStatus;
import org.summer.lawyer.constant.enums.PaymentMethod;
import org.summer.lawyer.domain.PayRefund;
import org.summer.lawyer.domain.bo.payorder.PayOrderBo;
import org.summer.lawyer.domain.bo.payrefund.PayRefundBo;
import org.summer.lawyer.domain.vo.payrefund.PayRefundVo;
import org.summer.lawyer.mapper.PayRefundMapper;
import org.summer.lawyer.service.IPayOrderService;
import org.summer.lawyer.service.IPayRefundService;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 退款订单Service业务层处理
 *
 * @author summer
 * @date 2024-06-22
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PayRefundServiceImpl extends ServiceImpl<PayRefundMapper, PayRefund>  implements IPayRefundService {

    private final IPayOrderService payOrderService;

    /**
     * 查询退款订单
     *
     * @param id 主键
     * @return 退款订单
     */
    @Override
    public PayRefundVo selectPayRefundVoById(Long id){
        return baseMapper.selectVoById(id);
    }

    @Override
    public PayRefundVo selectPayRefundVoByRefundNo(String refundNo) {
        LambdaQueryWrapper<PayRefund> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PayRefund::getRefundNo, refundNo);
        return baseMapper.selectVoOne(queryWrapper, false);
    }

    /**
     * 分页查询退款订单列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 退款订单分页列表
     */
    @Override
    public TableDataInfo<PayRefundVo> selectPageList(PayRefundBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PayRefund> lqw = buildQueryWrapper(bo);
        Page<PayRefundVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的退款订单列表
     *
     * @param bo 查询条件
     * @return 退款订单列表
     */
    @Override
    public List<PayRefundVo> selectPayRefundVoList(PayRefundBo bo) {
        LambdaQueryWrapper<PayRefund> lqw = Wrappers.lambdaQuery();
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PayRefund> buildQueryWrapper(PayRefundBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PayRefund> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getRefundNo() != null, PayRefund::getRefundNo, bo.getRefundNo());
        lqw.eq(bo.getPayNo() != null, PayRefund::getPayNo, bo.getPayNo());
        lqw.eq(bo.getAppId() != null, PayRefund::getAppId, bo.getAppId());
        lqw.eq(bo.getChannelId() != null, PayRefund::getChannelId, bo.getChannelId());
        lqw.eq(StrUtil.isNotBlank(bo.getChannelCode()), PayRefund::getChannelCode, bo.getChannelCode());
        lqw.eq(bo.getUserId() != null, PayRefund::getUserId, bo.getUserId());
        lqw.eq(StrUtil.isNotBlank(bo.getTradeNo()), PayRefund::getTradeNo, bo.getTradeNo());
        lqw.eq(bo.getOrderId() != null, PayRefund::getOrderId, bo.getOrderId());
        lqw.eq(bo.getPayWay() != null, PayRefund::getPayWay, bo.getPayWay());
        lqw.eq(bo.getRefundStatus() != null, PayRefund::getRefundStatus, bo.getRefundStatus());
        lqw.eq(bo.getPayTime() != null, PayRefund::getPayTime, bo.getPayTime());
        lqw.eq(bo.getPayStep() != null, PayRefund::getPayStep, bo.getPayStep());
        lqw.eq(bo.getPostStatus() != null, PayRefund::getPostStatus, bo.getPostStatus());
        lqw.eq(bo.getReturnStatus() != null, PayRefund::getReturnStatus, bo.getReturnStatus());
        lqw.eq(bo.getAmount() != null, PayRefund::getAmount, bo.getAmount());
        lqw.eq(bo.getRefundPrice() != null, PayRefund::getRefundPrice, bo.getRefundPrice());
        lqw.eq(StrUtil.isNotBlank(bo.getResultCode()), PayRefund::getResultCode, bo.getResultCode());
        lqw.eq(StrUtil.isNotBlank(bo.getResultMsg()), PayRefund::getResultMsg, bo.getResultMsg());
        lqw.eq(StrUtil.isNotBlank(bo.getPostJson()), PayRefund::getPostJson, bo.getPostJson());
        lqw.eq(StrUtil.isNotBlank(bo.getReturnJson()), PayRefund::getReturnJson, bo.getReturnJson());
        lqw.eq(bo.getReturnTime() != null, PayRefund::getReturnTime, bo.getReturnTime());
        lqw.eq(StrUtil.isNotBlank(bo.getNotifyUrl()), PayRefund::getNotifyUrl, bo.getNotifyUrl());
        lqw.eq(bo.getProcedureKb() != null, PayRefund::getProcedureKb, bo.getProcedureKb());
        lqw.eq(bo.getProcedureFee() != null, PayRefund::getProcedureFee, bo.getProcedureFee());
        lqw.eq(StrUtil.isNotBlank(bo.getMchNo()), PayRefund::getMchNo, bo.getMchNo());
        lqw.like(StrUtil.isNotBlank(bo.getMchName()), PayRefund::getMchName, bo.getMchName());
        lqw.eq(StrUtil.isNotBlank(bo.getExtParam()), PayRefund::getExtParam, bo.getExtParam());
        lqw.eq(StrUtil.isNotBlank(bo.getRefundReason()), PayRefund::getRefundReason, bo.getRefundReason());
        lqw.eq(bo.getSuccessTime() != null, PayRefund::getSuccessTime, bo.getSuccessTime());
        return lqw;
    }

    /**
     * 新增退款订单
     *
     * @param bo 退款订单
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(PayRefundBo bo) {
        PayRefund add = MapstructUtils.convert(bo, PayRefund.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtil.date());
        add.setUpdateTime(DateUtil.date());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改退款订单
     *
     * @param bo 退款订单
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(PayRefundBo bo) {
        PayRefund update = MapstructUtils.convert(bo, PayRefund.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtil.date());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PayRefund entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除退款订单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @DSTransactional(rollbackFor = Exception.class)
    @Override
    public void payRefundNotify(PayRefundVo vo) {
        PayRefundVo payRefundVo = selectPayRefundVoByRefundNo(vo.getRefundNo());
        if(payRefundVo != null && !Objects.equals(PayRefundStatus.SUCCESS.getCode(), payRefundVo.getRefundStatus())){
                PayRefund payRefund = new PayRefund();
                payRefund.setId(payRefundVo.getId());
                payRefund.setTradeNo(vo.getTradeNo());
                payRefund.setRefundStatus(PayRefundStatus.SUCCESS.getCode());
                payRefund.setPayWay(PaymentMethod.WECHAT_MINIAPP.getCode());
                payRefund.setPayTime(vo.getPayTime());
                payRefund.setPayStep(2);
                payRefund.setReturnStatus(1);
                payRefund.setReturnJson(vo.getReturnJson());
                payRefund.setReturnTime(vo.getReturnTime());
                payRefund.setResultCode(vo.getResultCode());
                payRefund.setResultMsg(vo.getResultMsg());
                payRefund.setSuccessTime(vo.getSuccessTime());
                payRefund.setUpdateTime(DateUtil.date());
            LambdaUpdateWrapper<PayRefund> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(PayRefund::getId, payRefund.getId());
            baseMapper.update(payRefund, updateWrapper);
            //处理支付订单
            PayOrderBo payOrderBo = new PayOrderBo();
            payOrderBo.setPayNo(payRefundVo.getPayNo());
            payOrderBo.setRefundPrice(payRefundVo.getRefundPrice());
            payOrderService.refundPayOrder(payOrderBo);
            //处理商品订单状态
        }
    }
}
